/**
 * @ngdoc overview
 * @name  wechat
 * @description
 *   微信对接模块
 */
angular.module('wechat', ['co'])

.constant('WECHAT_PUBLIC_APPID', 'wx4a2205ee65d28309')

/**
 * @ngdoc service
 * @name  wechat.WechatApi
 * @description
 *   微信相关接口服务
 */
.factory('WechatApi', function($http, $q, $window, Utils, API_APP_URL, WECHAT_PUBLIC_APPID) {

  var WECHAT_API_URL = API_APP_URL + '/wechat';

  var WechatApi = {
    getData: function() {
      if(this.data) {
        return $q.when(this.data);
      } else {
        return this.getInfo(this.openid).then(function(_res) {
          var res = _res.data;
          if(res.code === 0) {
            return $q.when(res.data);
          } else {
            return $q.reject();
          }
        });
      }
    },

    // 清理微信授权用参数
    cleanAuthParams: function(url) {
      var ret = url.replace(/([?&])code=([^&]*)(&?)/, function($0, $1) {
        return $1;
      });

      return ret.replace(/([?&])state=([^&]*)(&?)/, function($0, $1) {
        return $1;
      })
    },

    /**
     * @ngdoc    method
     * @name     wechat.WechatApi#getJsSdkSign
     * @methodOf wechat.WechatApi
     * @description 
     *    获取JS-SDK 签名参数
     *    res.data.noncestr
     *    res.data.timestamp
     *    res.data.signature
     * @param   {String}    url  用于生成签名的地址
     * @returns {Object}    $q.defer.promise
     */
    getJsSdkSign: function(url) {
      url = encodeURIComponent((url || $window.location.href).split('#')[0]);
      return $http.get(WECHAT_API_URL + '/getjssdksign?url=' + url);
    },

    /**
     * @ngdoc    method
     * @name     wechat.WechatApi#getOAuthUrl
     * @methodOf wechat.WechatApi
     * @description 
     *    获取授权地址
     *    res.data.url
     * @param   {String}    redirectUri  授权完后要跳转的地址，跳转时，会自动加上 code 和 state 参数
     * @param   {Boolean}   state         值等于 1 时原样返回 redirect_uri
     * @returns {Object}    $q.defer.promise
     */
    getOAuthUrl: function(redirectUri, state) {
      var url = WechatApi.cleanAuthParams(redirectUri);
      return $http.get(WECHAT_API_URL + '/getoauthurl?redirect_uri=' + encodeURIComponent(redirectUri) + '&state=' + (state || ''));
    },

    /**
     * @ngdoc    method
     * @name     wechat.WechatApi#getAuth
     * @methodOf wechat.WechatApi
     * @description 
     *    获取微信用户授权信息
     *    res.data.openid
     * @param   {String}    code          授权成功后返回的地址带过来的参数。
     * @returns {Object}    $q.defer.promise
     */
    getAuth: function(code) {
      return $http.get(WECHAT_API_URL + '/getauth?code=' + code);
    },

    /**
     * @ngdoc    method
     * @name     wechat.WechatApi#getInfo
     * @methodOf wechat.WechatApi
     * @description 
     *    获取微信用户资料
     *    res.data.openid
     * @param   {String}    openid            授权成功后返回的地址带过来的参数。
     * @returns {Object}    $q.defer.promise
     */
    getInfo: function(openid) {
      return $http.get(WECHAT_API_URL + '/getinfo?openid=' + openid);
    },

    /**
     * @ngdoc    method
     * @name     wechat.WechatApi#initJsSdk
     * @methodOf wechat.WechatApi
     * @description 
     *    初始化微信 JSSDK 
     * @param   {Object}    conf     配置
     */
    initJsSdk: function(conf) {
    	return WechatApi.getJsSdkSign().success(function(res) {
    	  if(res.code === 0) {
          if(typeof wx !== 'undefined') {
      	    wx.config(angular.extend({
              // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
              debug: false,
              // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
              jsApiList: [
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'onMenuShareQQ',
                'onMenuShareWeibo',
                // 'startRecord',
                // 'stopRecord',
                // 'onVoiceRecordEnd',
                // 'playVoice',
                // 'pauseVoice',
                // 'stopVoice',
                // 'onVoicePlayEnd',
                // 'uploadVoice',
                // 'downloadVoice',
                'chooseImage',
                'previewImage',
                // 'uploadImage',
                // 'downloadImage',
                // 'translateVoice',
                // 'getNetworkType',
                'openLocation',
                'getLocation',
                // 'hideOptionMenu',
                // 'showOptionMenu',
                // 'hideMenuItems',
                // 'showMenuItems',
                // 'hideAllNonBaseMenuItem',
                // 'showAllNonBaseMenuItem',
                // 'closeWindow',
                // 'scanQRCode',
                // 'chooseWXPay',
                // 'openProductSpecificView',
                // 'addCard',
                // 'chooseCard',
                // 'openCard'
              ] 
            }, conf, {
      	      appId: WECHAT_PUBLIC_APPID, // 必填，公众号的唯一标识
      	      timestamp: res.data.timestamp, // 必填，生成签名的时间戳
      	      nonceStr: res.data.noncestr, // 必填，生成签名的随机串
      	      signature: res.data.signature,// 必填，签名，见附录1
      	    }));
          }
    	  }  
    	})
    },

    /**
     * @ngdoc    method
     * @name     wechat.WechatApiinitShareConfig
     * @methodOf wechat.WechatApi
     * @description 
     *    初始化微信分享功能 
     * @param   {Object}    config     配置
     */
    initShareConfig: function(config) {
      wx.ready(function() {
        wx.onMenuShareAppMessage(config);
        wx.onMenuShareTimeline(config);
        wx.onMenuShareQQ(config);
        wx.onMenuShareWeibo(config);
      });
    }
  };

  return WechatApi;
})
